package biz

import (
	"context"
	pb "manage/api/exam"
	"time"

	"github.com/Fromsko/gouitls/logs"
	"github.com/go-kratos/kratos/v2/log"
)

var echo = logs.InitLogger()

func NewExamUsecase(repo ExamRepo, logger log.Logger) *ExamUsecase {
	return &ExamUsecase{repo: repo, log: log.NewHelper(logger)}
}

func (s *ExamUsecase) Create(ctx context.Context, req *pb.CreateExamRequest) (*pb.CreateExamResponse, error) {

	reply := &pb.CreateExamResponse{Code: 200, Msg: "创建成功"}

	resp, err := s.repo.CreateExam(&CreateRequest{
		ExamName:    req.ExamName,
		ExamTime:    req.ExamTime,
		ExamContent: req.ExamContent,
		TeacherID:   req.TeacherId,
	})
	if err != nil {
		reply.Code = 400
		reply.Msg = err.Error()
		echo.Warnf("创建错误:%v", err)
	} else {
		reply.ExamId = resp.ExamID
		reply.Msg = resp.Message
	}

	return reply, nil
}

func (s *ExamUsecase) Delete(ctx context.Context, req *pb.DeleteExamRequest) (*pb.DeleteExamResponse, error) {

	reply := &pb.DeleteExamResponse{Code: 200, Msg: "删除成功"}
	err := s.repo.DeleteExam(req.ExamId)
	if err != nil {
		reply.Code = 400
		reply.Msg = err.Error()
		echo.Errorf("删除: %s", reply.Msg)
	} else {
		echo.Infof("删除: %s", reply.Msg)
	}

	return reply, nil
}

func (s *ExamUsecase) Update(ctx context.Context, req *pb.UpdateExamRequest) (*pb.UpdateExamResponse, error) {

	reply := &pb.UpdateExamResponse{Code: 200, Msg: "更新成功"}
	err := s.repo.UpdateExam(&Exam{
		ExamID:      req.ExamId,
		UpdatedAt:   time.Now(),
		ExamTime:    req.ExamTime,
		TeacherID:   req.TeacherId,
		ExamContent: req.ExamContent,
	})
	if err != nil {
		reply.Code = 400
		reply.Msg = err.Error()
		echo.Errorf("更新: %s", reply.Msg)
	} else {
		echo.Infof("更新: %s", reply.Msg)
	}

	return reply, nil
}

func (s *ExamUsecase) Get(ctx context.Context, req *pb.GetExamRequest) (*pb.GetExamResponse, error) {

	reply := &pb.GetExamResponse{Code: 200, Msg: "查询成功"}
	resp, err := s.repo.GetExamInfo(req.ExamId)
	if err != nil {
		reply.Code = 400
		reply.Msg = err.Error()
		echo.Errorf("查询: %s", reply.Msg)
	} else {
		reply.ExamInfo = &pb.ExamInfo{
			ExamId:      resp.ExamID,
			ExamName:    resp.ExamName,
			ExamTime:    resp.ExamTime,
			ExamContent: resp.ExamContent,
			TeacherId:   resp.TeacherID,
		}
		echo.Infof("查询: %s", reply.Msg)
	}

	return reply, nil
}
